本篇內容參考自 Overreacted 網站的 "The WET Codebase"
在做開發時,你是不是也有這樣的習慣:
看到兩段長得「有點像」的程式,就立刻抽成共用?
Dan Abramov 在他的文章《The WET Codebase》中提醒我們:
為了 DRY(Don't Repeat Yourself)而抽象,常常會讓程式更難維護。
DRY 原則:Don't Repeat Yourself
→ 理念很好,強調可重用、避免重複邏輯。
WET 概念:Write Everything Twice
→ 並不是鼓勵你亂重複,而是提醒:
「別為了抽象而抽象」,有時候重複反而讓程式更清晰。
Dan 認為,共用邏輯應該是「觀察出來」的結果,而不是「預測出來」的需求。
function Text({ type, children }) {
const style =
type === "title"
? { fontSize: 24, fontWeight: "bold" }
: type === "subtitle"
? { fontSize: 18, color: "gray" }
: {};
return <p style={style}>{children}</p>;
}
看起來很 DRY,但實際上:
type
參數越來越多,邏輯越來越亂。function Title({ children }) {
return <p style={{ fontSize: 24, fontWeight: "bold" }}>{children}</p>;
}
function Subtitle({ children }) {
return <p style={{ fontSize: 18, color: "gray" }}>{children}</p>;
}
雖然重複了樣式,但:
這篇文章提醒我們:
Sometimes, duplication is better than the wrong abstraction.
I prefer to repeat code a few times and see if the pattern is truly stable before creating a shared component.
This keeps the code simple and easier to maintain.
中文
有時候重複比錯誤的抽象更好。
我會先讓重複自然發生,等到模式穩定後再抽共用,讓程式保持簡單、易懂、可維護。
重點 | 說明 |
---|---|
DRY 原則很好,但容易被誤用 | 不要因為重複而強行抽象 |
抽象要在模式穩定後進行 | 觀察重複,等待自然演化 |
可讀性比「行數少」更重要 | 程式是寫給人讀的 |
重複有時更健康 | 讓維護者敢改、懂得改 |